package com.zmn.plat.admin.controller.pilot;


import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.LayuiTableResponseDTO;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.manager.common.database.annotation.ReadOnlyConnection;
import com.zmn.plat.admin.controller.PlatBaseController;
import com.zmn.plat.manager.dictionary.OnePriceDict;
import com.zmn.plat.model.entity.pilot.ServCityPrice;
import com.zmn.plat.model.entity.pilot.ServCityPriceLog;
import com.zmn.plat.model.entity.pilot.ServCityPriceLogQuery;
import com.zmn.plat.model.entity.pilot.ServCityPriceQuery;
import com.zmn.plat.model.entity.servcategory.ServCategory;
import com.zmn.plat.services.interfaces.area.BaseAreaService;
import com.zmn.plat.services.interfaces.channel.ChannelService;
import com.zmn.plat.services.interfaces.pilot.ServCityPriceLogService;
import com.zmn.plat.services.interfaces.pilot.ServCityPriceService;
import com.zmn.plat.services.interfaces.servcategory.ServCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 城市试点基础查询Controller
 *
 * @author guoqiao
 * @since 2021-06-25 10:17:20
 */
@Slf4j
@RestController
@RequestMapping("/pilot/city")
public class ServCityPriceListController extends PlatBaseController {


    /**
     * 省parentId
     */
    public static final int AREA_PARENTID = 1;

    @Resource
    private ServCityPriceService servCityPriceService;

    @Autowired
    protected ChannelService channelService;

    @Autowired
    protected BaseAreaService baseAreaService;

    @Autowired
    protected ServCategoryService servCategoryService;

    @Autowired
    protected ServCityPriceLogService logService;


    /**
     * 描述: 查询列表
     *
     * @author guoqiao
     * @since 2021-06-25 10:17:20
     */
    @RequestMapping(value = "/list")
    @ReadOnlyConnection
    public ModelAndView list(@ModelAttribute ServCityPriceQuery query) {

        List<ServCityPrice> items = servCityPriceService.listPageByQuery(query);
        ModelAndView mav = new ModelAndView("pilot/city/list");

        mav.addObject("payTypeList", OnePriceDict.getPayTypeList());
        mav.addObject("statusList", GlobalDict.getStatusList(false));
        mav.addObject("provinces", getAreaList(AREA_PARENTID));
        mav.addObject("cityList", (query.getProvinceId() == null ? null : getAreaList(query.getProvinceId())));
        mav.addObject("typeList", OnePriceDict.getTypeList());
        mav.addObject("vo", query);
        mav.addObject("items", items);

        return mav;
    }

    /**
     * 城市配置查询
     *
     * @param query the query
     * @return layui table response dto
     */
    @RequestMapping(value = "/ajax/list")
    @ResponseBody
    @ReadOnlyConnection
    public LayuiTableResponseDTO ajaxList(ServCityPriceQuery query) {

        Integer count = servCityPriceService.countByQuery(query);
        List<ServCityPrice> items = count > 0 ? servCityPriceService.listPageByQuery(query) : new ArrayList<>();

        return new LayuiTableResponseDTO<>(StatusConsts.STATUS_SUCCESS, "OK", count, items);
    }

    /**
     * 描述: 详情
     *
     * @author guoqiao
     * @since 2021-06-25 10:17:20
     */
    @RequestMapping("/addEditView")
    public ModelAndView info(@RequestParam(value = "relationId") Integer relationId) {

        ServCityPrice servCityPrice = NumberUtil.isNullOrZero(relationId) ? new ServCityPrice() : servCityPriceService.findById(relationId);
        ModelAndView mv = new ModelAndView("pilot/servcityprice/detail");
        if (NumberUtil.isNullOrZero(servCityPrice.getDepositDeductionAmount())){
            servCityPrice.setDepositDeductionAmount(null);
        }
        mv.addObject("servCityPrice", servCityPrice);

        return mv;
    }

    /**
     * 描述: 新增配置
     *
     * @return modelAndView
     * @author xiangjunming
     * @since 2019/11/19 11:10
     */
    @RequestMapping(value = "add")
    public ModelAndView add() {

        ModelAndView mav = new ModelAndView("pilot/add");
        mav.addObject("typeList", OnePriceDict.getTypeList());
        mav.addObject("type", 2);

        return mav;
    }

    /**
     * 下一步，或者编辑与新增
     *
     * @param relationId 城市配置id
     * @param type       类型
     * @return
     */
    @RequestMapping(value = "toEdit")
    @ReadOnlyConnection
    public ModelAndView toEdit(Integer relationId, Integer type) {

        ModelAndView mav = new ModelAndView("pilot/city/detail");

        ServCityPrice byKey = Optional.ofNullable(relationId)
                .map(p -> servCityPriceService.findById(p))
                .orElse(new ServCityPrice() {{
                    setType(type);
                }});

        // 如果没有设置定金则默认为0
        byKey.setDeposit(NumberUtil.isNullOrZero(byKey.getDeposit()) ? null : byKey.getDeposit());

        mav.addObject("depositList", OnePriceDict.getDepositList());
        mav.addObject("item", byKey);
        mav.addObject("payTypeList", OnePriceDict.getPayTypeList());
        mav.addObject("statusList", GlobalDict.getStatusList(false));
        mav.addObject("provinces", getAreaList(AREA_PARENTID));
        mav.addObject("typeList", OnePriceDict.getTypeList());

        return mav;
    }

    /**
     * 检查城市ID是否已配置
     *
     * @param provinceId the province id
     * @param cityId     the city id
     * @return result dto
     */
    @RequestMapping(value = "checkCity")
    @ResponseBody
    @ReadOnlyConnection
    public ResponseDTO checkCity(@RequestParam(value = "provinceId", defaultValue = "0") Integer provinceId,
                                 @RequestParam(value = "cityId", defaultValue = "0") Integer cityId, Integer type) {

        ServCityPriceQuery query = new ServCityPriceQuery();
        query.setProvinceId(provinceId);
        query.setType(type);
        List<ServCityPrice> servCityPrices = servCityPriceService.listByQuery(query);

        boolean flag = false;
        String checkMsg = "已在其他配置项中开通，不支持重复选择！";
        for (ServCityPrice item : servCityPrices) {
            if (Objects.equals(item.getCityId(), cityId)) {
                flag = true;
            } else if (Objects.equals(item.getProvinceId(), provinceId) && item.getCityId() == null) {
                flag = true;
                checkMsg = "父级城市已在其他配置项中开通！";
            } else if (Objects.equals(item.getProvinceId(), provinceId) && cityId == null) {
                flag = true;
                checkMsg = "子级城市已在其他配置项中开通！";
            }
        }
        if (flag) {
            return ResponseDTO.fail(checkMsg);
        }
        return ResponseDTO.success(true, "添加成功！");
    }

    /**
     * to详情
     *
     * @param relationId the relation id
     * @return model and view
     */
    @RequestMapping(value = "detail")
    @ReadOnlyConnection
    public ModelAndView detail(Integer relationId, Integer type) {

        ModelAndView mav = this.toEdit(relationId, type);
        ServCityPriceLogQuery logQuery = new ServCityPriceLogQuery();
        logQuery.setRelationId(relationId);
        List<ServCityPriceLog> logs = logService.listByQuery(logQuery);
        mav.addObject("isDetail", true);
        mav.addObject("logs", logs);

        return mav;
    }

    /**
     * 获取地区列表
     *
     * @param parentId 父级ID
     * @return
     * @author yangshuangping
     * @since 2021-6-25 16:05:10
     */
    protected List<VtDTO> getAreaList(Integer parentId) {

        return Optional.ofNullable(baseAreaService.listByParentId(parentId))
                .map(p -> p.stream()
                        .map(t -> new VtDTO(t.getAreaId(), t.getName()))
                        .collect(Collectors.toList()))
                .orElse((List<VtDTO>) Collections.EMPTY_LIST);
    }

    /**
     * 描述: 获取所有的服务分类 转换为VtDto 默认将状态设置为 false
     *
     * @param collect 服务分类ID List<Integer> categId
     * @param status  是否有效
     * @return java.util.List<VtDTO>
     * @author yangshuangping
     * @since 2021-6-25 16:05:10
     */
    protected List<VtDTO> getAllServCategShowName(List<Integer> collect, boolean status) {

        ServCategory servCategory = new ServCategory();
        servCategory.setShowStatus(GlobalDict.YESNO_YES);
        return servCategoryService.listByQuery(servCategory).stream()
                .map(mm -> new VtDTO(mm.getCategId(), mm.getShowName(), collect.contains(mm.getCategId()) ? status : false))
                .collect(Collectors.toList());
    }
}
